package org.example.classtopia.InterCeptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.classtopia.Utils.ThreadLocalUtil;
import org.example.classtopia.Utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
@Slf4j
@Service
public class AuthHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenUtils tokenUtils;

    @Value("${token.expireTime}")
    private Long expireTime;

    @Value("${token.refreshTime}")
    private Long refreshTime;

    @Override
    public boolean preHandle (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception{
        if(!(object instanceof HandlerMethod)) return true;
        
        String token = httpServletRequest.getHeader("token");
        
        if(token == null || token.trim().isEmpty()) {
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            return false;
        }
        
        try {
            Map<String, String> map = tokenUtils.parseToken(token);
            String userId = map.get("userId");
            String userRole = map.get("userRole");

            // 关键修复：将解析出的用户ID存入ThreadLocal，以便后续业务逻辑使用
            ThreadLocalUtil.set(Long.valueOf(userId));

            long timeOfUse = System.currentTimeMillis() - Long.parseLong(map.get("timeStamp"));
            if(timeOfUse < refreshTime) {
                return true; //Token验证成功
            }
            else if(timeOfUse < expireTime){
                httpServletResponse.setHeader("token", tokenUtils.getToken(userId, userRole));
                return true; //Token刷新成功
            }
            else{
                httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
                return false; // Token过期
            }
        } catch (Exception e) {
            // 捕获Token解析失败等异常，返回401
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完毕后，清理ThreadLocal，防止内存泄漏
        ThreadLocalUtil.remove();
    }
}
